package com.example.demo.leetcode.level2;


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class 删除链表倒数第N个节点 {
    public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

    public ListNode removeNthFromEnd(ListNode head, int n) {

        if(head.next == null && n == 1){
            return null;
        }

        int count = 0;
        ListNode node = head;
        ListNode node2 = head;
        ListNode end = head;

        while(node != null){
            node = node.next;
            count++;
        }
        int m = count - n;
        for(int i=0;i<m-1;i++){
            node2 = node2.next;
        }

        if(count == n){
            end = node2.next;
        }
        node2.next = node2.next.next;
        return end;
    }
}
